package com.meirengu.webview.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.utils.RequestUtil;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-05-24 15:58
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    KwUserChannelService kwUserChannelService;


    @Autowired
    private KwThirdbackService kwThirdbackService;

    @Autowired
    KwProductService kwProductService;

    @Autowired
    private LmUserBaseService lmUserBaseService;

    @Autowired
    private InformationService informationService;

    /**
     * 平安备案展示页
     *
     * @return
     */
    @RequestMapping(value = "show", method = RequestMethod.GET)
    public String show() {
        return "signUp2";
    }

    /**
     * 春雨备案展示页
     *
     * @return
     */
    @RequestMapping(value = "show2", method = RequestMethod.GET)
    public String show2() {
        return "signUpRain";
    }

    /**
     * 平安备案展示页
     *
     * @return
     */
    @RequestMapping(value = "pingan1", method = RequestMethod.GET)
    public String pingan1() {
        return "pingan1";
    }

    /**
     * 平安备案展示页
     *
     * @return
     */
    @RequestMapping(value = "pingan2", method = RequestMethod.GET)
    public String pingan2() {
        return "pingan2";
    }

    /**
     * 平安页
     *
     * @return
     */
    @RequestMapping(value = "baseIndex2", method = RequestMethod.GET)
    public String baseIndex2() {
        return "baseIndex2";
    }

    /**
     * 注册页
     *
     * @return
     */
    @RequestMapping(value = "signUp", method = RequestMethod.GET)
    public String signup() {
        return "signUp";
    }

    /**
     * 倒流页
     *
     * @return
     */
    @RequestMapping(value = "baseIndex", method = RequestMethod.GET)
    public String baseIndex() {
        return "baseIndex";
    }

    /**
     * 倒流页
     *
     * @return
     */
    @RequestMapping(value = "baseIndexUnion", method = RequestMethod.GET)
    public ModelAndView baseIndexUnion(@RequestParam(required = false) String tel) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        List<Map<String, Object>> list = kwProductService.getList(params);
        int pinganphflag = 1;
        int newloanflag = 1;
        int ztxflag = 1;
        try {
            if (StringUtils.isNotBlank(tel)) {
                params.put("mobile", tel);
                List<Map<String, Object>> channellist = kwUserChannelService.getList(params);
                if (channellist != null && channellist.size() > 0) {
                    for (int i = 0; i < channellist.size(); i++) {
                        String channelCode = channellist.get(i).get("channelCode").toString();
                        String suited = channellist.get(i).get("suited").toString();
                        if ("pinganpuhui".equals(channelCode) && "N".equals(suited)) {
                            pinganphflag = 0;
                        } else if ("paca".equals(channelCode) && "N".equals(suited)) {
                            newloanflag = 0;
                        } else if ("ztx".equals(channelCode) && "N".equals(suited)) {
                            ztxflag = 0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String param = String.format("参数:mobile:%s", String.valueOf(tel));
            logger.error(">> UserController.baseIndexUnion throw exception: {}", ExceptionUtils.getFullStackTrace(e), param);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("pinganphflag", pinganphflag);
        result.put("newloanflag", newloanflag);
        result.put("ztxflag", ztxflag);
        return new ModelAndView("baseIndexUnion", result);
    }


    @ResponseBody
    @RequestMapping(value = "signUp", method = RequestMethod.POST)
    public Result signUp(HttpServletRequest request,
                         @RequestParam(required = true) String phoneno,
                         @RequestParam(required = true) String name,
                         @RequestParam(required = true) Integer sex,
                         @RequestParam(required = true) String city,
                         @RequestParam(required = true) String birthday,
                         @RequestParam(required = true) String cid) {
        try {

            Integer flag = userService.isExist(phoneno);
            if (flag != null && flag == 1) {
                return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
            }
            String ip = RequestUtil.getClientIp(request);
            userService.signUp(phoneno, name, sex, city, birthday, cid, ip);
            return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数：phoneno:%s,name:%s,sex:%s,city:%s,birthday:%s,cid:%s", phoneno,
                    name, String.valueOf(sex), city, birthday, cid);
            logger.error(">> UserController.signUp throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }

    }


    @ResponseBody
    @RequestMapping(value = "complement", method = RequestMethod.POST)
    public Result complement(HttpServletRequest request) {
        try {
            String param = request.getParameter("p");
            JSONObject paramJson = JSON.parseObject(param);
            //手机号
            String phoneno = paramJson.getString("phoneno");
            //姓名
            String name = paramJson.getString("name");
            //期望金额
            BigDecimal money = paramJson.getBigDecimal("money");
            //性别
            Integer sex = paramJson.getInteger("sex");
            //所在城市
            String city = paramJson.getString("city");
            //职业
            Integer profession = paramJson.getInteger("profession");
            //社保
            Integer socialSecurity = paramJson.getInteger("socialSecurity");
            //住房公积金
            Integer housingFund = paramJson.getInteger("housingFund");
            //生日
            Date birthday = paramJson.getDate("birthday");
            //月薪
            Integer income = paramJson.getInteger("income");
            //勾选意外险
            Integer insurance = paramJson.getInteger("insurance");
            //名下房产
            Integer housingType = paramJson.getInteger("housingType");
            //名下车
            Integer hasCar = paramJson.getInteger("hasCar");
            //信用情况
            Integer creditSituation = paramJson.getInteger("creditSituation");
            //工资发放方式
            Integer paytype = paramJson.getInteger("paytype");
            //工作时长
            Integer worklong = paramJson.getInteger("worklong");
            //接受用户协议
            Integer acceptsafety = paramJson.getInteger("acceptsafety");
            String infoJson = paramJson.getString("info");

            Integer enpass = 1;
            //寿险
            Integer lifeInsurance = paramJson.getInteger("lifeInsurance");
            //微粒贷是否借款
            Integer auditBy = paramJson.getInteger("auditBy");
            //平台
            String plantform = paramJson.getString("plantform");
            //渠道
            String channel = paramJson.getString("channel");
            //渠道号
            String cid = paramJson.getString("cid");
            String requestid = paramJson.getString("requestid");
            String referer = paramJson.getString("referer");
            String fromUrl = paramJson.getString("fromUrl");

            Integer flag = userService.isExist(phoneno);
            if (flag != null && flag == 1) {
                return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
            }

            User user = new User();
            user.setMobile(phoneno);
            user.setName(name);
//            user.setPassword();
            user.setSex(sex);
            user.setChannelId("");
            user.setChannelCode(cid);
            user.setChannelName("默认渠道");
            userService.insert(user);

            //用户详细信息
            UserInfo userInfo = new UserInfo();
//            userInfo.setRealName();
//            userInfo.setIdType();
//            userInfo.setIdCard();
//            userInfo.setProvince();
//            userInfo.setCity();
//            userInfo.setArea();
//            userInfo.setAddress();
            userInfo.setExpectAmount(money);
            userInfo.setPolicy(lifeInsurance);
            userInfo.setCredit(creditSituation);
            userInfo.setHouse(housingType);
            userInfo.setCar(hasCar);
            userInfo.setFund(housingFund);
            userInfo.setSocialSecurity(socialSecurity);
            userInfo.setOccupation(profession);
            userInfo.setSalaryMethod(paytype);
            userInfo.setWorkDuration(worklong);
            userInfo.setSalary(income);
            userInfo.setWxloan(auditBy);
            userInfo.setScity(city);
            userInfo.setBirthday(birthday);
            userInfo.setBusinessDuration(enpass);
            userInfo.setUserId(user.getId());
            userInfoService.insert(userInfo);
//            //先查重
//            int repeatNum = signupActivityService.check(telphone, type);
//            if(repeatNum > 0){
//                return super.setResult(StatusCode.TELPHONE_EXIST, "", StatusCode.codeMsgMap.get(StatusCode.TELPHONE_EXIST));
//            }
//
//            signupActivityService.insert(activity);
            return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:param:%s", String.valueOf(request.getParameter("p")));
            logger.error(">> UserController.complement throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }

    }

    /**
     * toProgress
     *
     * @return
     */
    @RequestMapping(value = "toProgress", method = RequestMethod.GET)
    public String toProgress() {
        return "progress/index";
    }

    /**
     * toProgress
     *
     * @return
     */
    @RequestMapping(value = "toResult", method = RequestMethod.GET)
    public String toResult() {
        return "progress/result";
    }


    /**
     * 查询贷款进度
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "progress", method = RequestMethod.POST)
    public Result progress(@RequestParam(required = true) String mobile) {
        try {

            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isNotBlank(mobile)) {
                map.put("mobile", mobile);
            }
            map.put("code", 1);
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            Map<String, Object> userMap = new HashMap<String, Object>();
            User user = userService.getByMobile(mobile);
            if (user != null) {
                userMap.put("name", user.getName());
                userMap.put("createDate", user.getCreateDate());
                dataList.add(userMap);
                List<Map<String, Object>> thirdbackList = kwThirdbackService.getList(map);
                if (thirdbackList != null && thirdbackList.size() > 0) {
                    for (Map<String, Object> thirdbackMap : thirdbackList) {
                        String interfaceCode = thirdbackMap.get("interfaceCode").toString();
                        if ("pinganph".equals(interfaceCode)) {
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put("interfaceName", "平安普惠");
                            dataMap.put("createDate", thirdbackMap.get("createDate"));
                            dataList.add(dataMap);
                        } else if ("newloan".equals(interfaceCode)) {
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put("interfaceName", "平安新一贷");
                            dataMap.put("createDate", thirdbackMap.get("createDate"));
                            dataList.add(dataMap);
                        } else if ("ZTX".equals(interfaceCode)) {
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put("interfaceName", "中腾信");
                            dataMap.put("createDate", thirdbackMap.get("createDate"));
                            dataList.add(dataMap);
                        } else if ("zhudai".equals(interfaceCode)) {
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put("interfaceName", "助贷网");
                            dataMap.put("createDate", thirdbackMap.get("createDate"));
                            dataList.add(dataMap);
                        } else if ("eastfinance-register".equals(interfaceCode)) {
                            Map<String, Object> dataMap = new HashMap<String, Object>();
                            dataMap.put("interfaceName", "东方融资网");
                            dataMap.put("createDate", thirdbackMap.get("createDate"));
                            dataList.add(dataMap);
                        }
                    }
                }
            }
            return super.setResult(StatusCode.OK, dataList, StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> UserController.progress throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }

    }


    /**
     * 查询该用户是否注册
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "is_exist", method = RequestMethod.POST)
    public Result isExist(@RequestParam(required = false) String mobile) {
        boolean flag = false;
        try {
            flag = informationService.isExist(mobile);
            if (flag) {
                return super.setResult(StatusCode.USER_IS_EXITS, null, StatusCode.codeMsgMap.get(StatusCode.USER_IS_EXITS));
            }
            return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:mobile:%s", mobile);
            logger.error(">> UserController.is_exist throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }

    }


}
